﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace Downloader.Framework.Extensions
{
    public static class StringExtensions
    {



        public static Encoding chnEncoding = Encoding.GetEncoding("GB2312");

        public static string ToHtmlFormat(this string str)
        {
            return str.Replace("\r\n", "<br />");
        }

        public static bool NotNullAndEmpty(this string str)
        {
            return !string.IsNullOrEmpty(str);
        }
        public static bool IsNull(this string str)
        {
            return str == null;
        }
        public static bool IsEmpty(this string str)
        {
            return str == string.Empty;
        }
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        public static int GetByteLen(this string str)
        {
            return chnEncoding.GetByteCount(str);
        }
        public static bool IsRelativeToDefaultPath(this string file)
        {
            return !(file.StartsWith("~", StringComparison.Ordinal) ||
                file.StartsWith("../", StringComparison.Ordinal) ||
                file.StartsWith("/", StringComparison.Ordinal) ||
                file.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
                file.StartsWith("https://", StringComparison.OrdinalIgnoreCase));
        }

        public static string Left(this string str, int len)
        {
            if (str.Length <= len) return str;
            return str.Substring(0, len);
        }
        public static string Right(this string str, int len)
        {
            if (str.Length <= len) return str;
            return str.Substring(str.Length - len);
        }

        public static string FormatWith(this string theString, params object[] args)
        {
            return string.Format(theString, args);
        }

        public static string Left(this string str, int len, string endtag)
        {
            if (str.Length <= len) return str;
            return str.Substring(0, len) + endtag;

        }

        public static string LeftBytes(this string s, int l)
        {
            string temp = s;
            if (s.GetByteLen() <= l)
            {
                return temp;
            }
            for (int i = temp.Length; i >= 0; i--)
            {
                var str = temp.Substring(0, i);
                if (str.GetByteLen() <= l)
                {
                    return str;
                }
            }
            return "";
        }

        public static string ToJson(this object item)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(item);
        }

        /// <summary>
        /// 对字符串进行截字，截去字的部分用"..."替代
        /// </summary>
        /// <remarks>
        /// 一个字符指双字节字符，单字节字符仅算半个字符
        /// </remarks>
        /// <param name="rawString">待截字的字符串</param>
        /// <param name="charLimit">截字的长度，按双字节计数</param>
        /// <returns>截字后的字符串</returns>
        public static string Trim(this string rawString, int charLimit)
        {
            return Trim(rawString, charLimit, "...");
        }
        /// <summary>
        /// 对字符串进行截字(区分单字节及双字节字符)
        /// </summary>
        /// <remarks>
        /// 一个字符指双字节字符，单字节字符仅算半个字符
        /// </remarks>
        /// <param name="rawString">待截字的字符串</param>
        /// <param name="charLimit">截字的长度，按双字节计数</param>
        /// <param name="appendString">截去字的部分用替代字符串</param>
        /// <returns>截字后的字符串</returns>
        public static string Trim(this string rawString, int charLimit, string appendString)
        {
            if (string.IsNullOrEmpty(rawString) || rawString.Length <= charLimit)
            {
                return rawString;
            }
            int num = System.Text.Encoding.UTF8.GetBytes(rawString).Length;
            if (num <= charLimit * 2)
            {
                return rawString;
            }
            charLimit = charLimit * 2 - System.Text.Encoding.UTF8.GetBytes(appendString).Length;
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            int num2 = 0;
            for (int i = 0; i < rawString.Length; i++)
            {
                char c = rawString[i];
                stringBuilder.Append(c);
                num2 += ((c > '\u0080') ? 2 : 1);
                if (num2 >= charLimit)
                {
                    break;
                }
            }
            return stringBuilder.Append(appendString).ToString();
        }
        /// <summary>
        /// Unicode转义序列
        /// </summary>
        /// <param name="rawString">待编码的字符串</param>
        public static string UnicodeEncode(this string rawString)
        {
            if (rawString == null || rawString == string.Empty)
            {
                return rawString;
            }
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            for (int i = 0; i < rawString.Length; i++)
            {
                int num = (int)rawString[i];
                string text;
                if (num > 126)
                {
                    stringBuilder.Append("\\u");
                    text = num.ToString("x");
                    for (int j = 0; j < 4 - text.Length; j++)
                    {
                        stringBuilder.Append("0");
                    }
                }
                else
                {
                    text = ((char)num).ToString();
                }
                stringBuilder.Append(text);
            }
            return stringBuilder.ToString();
        }
        /// <summary>
        /// 清除xml中的不合法字符
        /// </summary>
        /// <remarks>
        /// <para>无效字符：</para>
        /// <list type="number">
        /// <item>0x00 - 0x08</item>
        /// <item>0x0b - 0x0c</item>
        /// <item>0x0e - 0x1f</item>
        /// </list>        
        /// </remarks>
        /// <param name="rawXml">待清理的xml字符串</param>
        public static string CleanInvalidCharsForXML(this string rawXml)
        {
            if (string.IsNullOrEmpty(rawXml))
            {
                return rawXml;
            }
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            char[] array = rawXml.ToCharArray();
            for (int i = 0; i < array.Length; i++)
            {
                int num = System.Convert.ToInt32(array[i]);
                if ((num < 0 || num > 8) && (num < 11 || num > 12) && (num < 14 || num > 31))
                {
                    stringBuilder.Append(array[i]);
                }
            }
            return stringBuilder.ToString();
        }
        /// <summary>
        /// 清理Sql注入特殊字符
        /// </summary>
        /// <remarks>
        /// 需清理字符：'、--、exec 、' or
        /// </remarks>
        /// <param name="sql">待处理的sql字符串</param>
        /// <returns>清理后的sql字符串</returns>
        public static string StripSQLInjection(this string sql)
        {
            if (!string.IsNullOrEmpty(sql))
            {
                string pattern = "((\\%27)|(\\'))\\s*((\\%6F)|o|(\\%4F))((\\%72)|r|(\\%52))";
                string pattern2 = "(\\%27)|(\\')|(\\-\\-)";
                string pattern3 = "\\s+exec(\\s|\\+)+(s|x)p\\w+";
                sql = Regex.Replace(sql, pattern, string.Empty, RegexOptions.IgnoreCase);
                sql = Regex.Replace(sql, pattern2, string.Empty, RegexOptions.IgnoreCase);
                sql = Regex.Replace(sql, pattern3, string.Empty, RegexOptions.IgnoreCase);
                sql = sql.Replace("%", "[%]");
            }
            return sql;
        }

    }
    public static class IntExtentions
    {
        public static int ToBitLevel(this int level)
        {
            return (int)Math.Pow(2, level - 1);
        }
    }
}
